package cppweb.spring.utils;

import stdx.Utils;
import java.lang.reflect.Method;

public class DatabaseHelper {
    public static void insertSelective(Object mapper, Object record) throws Exception{
        insertSelective(mapper, record, 5);
    }
    public static void insertSelective(Object mapper, Object record, int trytimes) throws Exception{
        Method setId = record.getClass().getMethod("setId", Long.class);
        Method insertSelective = mapper.getClass().getMethod("insertSelective", record.getClass());
        while (true){
            setId.invoke(record, DateSequence.get());
            try {
                insertSelective.invoke(mapper, record);
                break;
            }
            catch (Exception e){
                if (--trytimes <= 0) throw e;

                String msg = e.getMessage();

                if (Utils.IsEmpty(msg)){
                    if (e.getCause() == null) throw e;

                    if (Utils.IsEmpty(msg = e.getCause().getMessage())) throw e;
                }

                if (msg.toLowerCase().indexOf("duplicate") < 0) throw e;
            }
        }
    }
}